import { reactive, ref } from 'vue'
import { checklistChecklistPageApi, checklistChecklistAddApi, checklistRemoveApi } from '@/api/01work/01stage'
import { checkListData } from '@/api/01work/01type'
import { ElMessage, ElMessageBox } from 'element-plus'
import useInstance from '@/hooks/useInstance';
export default function useCheckList() {
  // 需要什么东西 知道吗 打开弹框第一步
  const RefCkenList = ref<{ show: (row?: any) => void }>()
  const {global} = useInstance()
  const checkListData = reactive<checkListData>({
    list: [],
    Loading: false,
    row: {}
  })
  const editEcheckList = async (row) => {
    checkListData.Loading = true
    checkListData.row = row
    RefCkenList.value?.show(row)
    const res = await checklistChecklistPageApi({ analyseId: row.id })
    if (res.code === 200) {
      checkListData.Loading = false
      checkListData.list = res.data
    }
  }
  // 为什么数据为空 是什么问题导致的
  const addBtns = (row) => {
    console.log('addbtn----', checkListData, row);
    ElMessageBox.prompt('请输入检查单名称', '检查的名称', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: row?.name,
      inputValidator: (value) => {
        if (value === null || value === '' || value.length > 24) {
          return '检查单名称不能为空, 最多可输入25个字符'
        } else if (!value.match('^[a-zA-Z0-9_\u4e00-\u9fa5]+$')) {
          return '不支持特殊字符'
        } else {
          return true
        }
      },
      inputErrorMessage: '请输入正确格式',
    })
      .then(({ value }) => {
        console.log(value, row);

        if (row?.id) {
          checklistChecklistAddApi({ id: row.id, name: value }).then((res) => {
            if (res.code === 200) {
              editEcheckList({ id: checkListData.row.id })
              ElMessage({
                type: 'success',
                message: '检查单新增成功',
              })
            }
          })
        } else {
          checklistChecklistAddApi({ analyseId: checkListData.row.id, name: value }).then((res) => {
            if (res.code === 200) {
              editEcheckList({ id: checkListData.row.id })
              ElMessage({
                type: 'success',
                message: '检查单新增成功',
              })
            }
          })
        }
      })
      .catch((err) => {
        console.log(err);

        ElMessage({
          type: 'info',
          message: 'Input canceled',
        })
      })
  }
  const deleteBtns = async (id) => {
    const params = {
      id: id,
      type: 1
    }
    const confirm = await global.$myconfirm('你确定需要删除嘛?')
    if (confirm) {
      const res = await checklistRemoveApi(params)
      if (res.code === 200) {
        global.$message({ message: '删除成功', type: 'success' })
        editEcheckList({ id: checkListData.row.id })
      }
    } else {
      global.$message({ message: '已取消删除', type: 'warning' })
    }
  }
  return {
    RefCkenList, editEcheckList, checkListData, addBtns, deleteBtns
  }
}